//
//  BJLoginViewController.m
//  BowJoy
//
//  Created by  on 2024/5/13.
//

#import "BJLoginViewController.h"
#import "BJTabBarViewController.h"
#import <AuthenticationServices/AuthenticationServices.h>
#import "BJLoginNoticePopView.h"
#import "BJWebContentViewController.h"
@interface BJLoginViewController ()<ASAuthorizationControllerDelegate, ASAuthorizationControllerPresentationContextProviding,BJLoginNoticePopViewDelegate>
@property (nonatomic) YYLabel *PrivacyPolicyLb;
@property (nonatomic) UIImageView *agreeIv;

@property (nonatomic) UIView *desBgView;

@property (nonatomic) BOOL isAgree;

@property (nonatomic) BOOL isAppleLogin;

@property (weak, nonatomic) IBOutlet UIView *fastLoginView;
@property (weak, nonatomic) IBOutlet UIView *appidLoginView;

@end

@implementation BJLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.addChild(self.desBgView);
    self.desBgView.addChild(self.PrivacyPolicyLb);
    self.desBgView.addChild(self.agreeIv);
    
    self.desBgView.makeCons(^{
        make.centerX.constants(0);
        make.bottom.constants(-34-20);
        make.height.constants(45);
    });
    
    self.agreeIv.makeCons(^{
        make.leading.constants(0);
        make.width.height.constants(18);
        make.top.constants(2);
    });
    
    self.PrivacyPolicyLb.makeCons(^{
        make.leading.view(self.agreeIv).trailing.constants(0);
        make.trailing.constants(-5);
        make.top.constants(2);
    });
    
//    __weak typeof(self) weakSelf = self;
    self.agreeIv.onClick(^{
        self.isAgree = !self.isAgree;

        [self.agreeIv setImage:[UIImage imageNamed:self.isAgree ? @"ic_agree_select" : @"ic_agree_unSelect"]];
    });
    
    self.fastLoginView.onClick(^{

        if (!self.isAgree){
            BJLoginNoticePopView *guidePopView = [[BJLoginNoticePopView alloc]init];
            guidePopView.delegate = self;
            self.isAppleLogin = NO;
            [guidePopView showView];
            return;
        }
        [ASHUD showASLoading];
        [self gotoLoginWithLoginType:YES token:[UUIDStrengthen getDeviceIDInKeychain]];
    });
    
    self.appidLoginView.onClick(^{
        if (!self.isAgree){
            BJLoginNoticePopView *guidePopView = [[BJLoginNoticePopView alloc]init];
            guidePopView.delegate = self;
            self.isAppleLogin = YES;
            [guidePopView showView];
            return;
        }
        [self loginWithAppleId];
    });

    [self addReachabilityManager];

}
/**
 实时检查当前网络状态
 */
- (void)addReachabilityManager {
    AFNetworkReachabilityManager *afNetworkReachabilityManager = [AFNetworkReachabilityManager sharedManager];
    [afNetworkReachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusNotReachable:{
//                NSLog(@"网络不通：%@",@(status) );
            
                break;
            }
            case AFNetworkReachabilityStatusReachableViaWiFi:{
//                NSLog(@"网络通过WIFI连接：%@",@(status));
                break;
            }
            case AFNetworkReachabilityStatusReachableViaWWAN:{
//                NSLog(@"网络通过无线连接：%@",@(status) );
                break;
            }
            default:
                break;
        }
    }];
      
    [afNetworkReachabilityManager startMonitoring];  //开启网络监视器；
}

-(void)agreeLoginNoticePopView{
    
    [ASHUD showASLoading];
    self.isAgree = YES;

    [self.agreeIv setImage:[UIImage imageNamed:self.isAgree ? @"ic_agree_select" : @"ic_agree_unSelect"]];

    if(self.isAppleLogin == YES){
        
        [self loginWithAppleId];
        NSMutableArray *dataList = [NSMutableArray array];
        NSDictionary *dict = @{
            @"page":@"applelogin",
            @"duration":@(0),
            @"event":@"pv",
            @"tm":@([[BJNetManager shareNetManager] gs_getCurrentTimeToMilliSecond]),
        };
        [dataList addObject:dict];
        [[BJNetManager shareNetManager]postLogWithParam:dataList];
        


    }else{
//        self.fastLoginBtn.enabled = NO;
        //登录
        [self gotoLoginWithLoginType:YES token:[UUIDStrengthen getDeviceIDInKeychain]];
        
        NSMutableArray *dataList = [NSMutableArray array];
        NSDictionary *dict = @{
            @"page":@"quicklogin",
            @"duration":@(0),
            @"event":@"pv",
            @"tm":@([[BJNetManager shareNetManager] gs_getCurrentTimeToMilliSecond]),
        };
        [dataList addObject:dict];
        [[BJNetManager shareNetManager]postLogWithParam:dataList];

    }
    
}


- (void)loginWithAppleId{
    if (@available(iOS 13.0, *)) {
        ASAuthorizationAppleIDProvider *provider = [[ASAuthorizationAppleIDProvider alloc] init];
        ASAuthorizationAppleIDRequest *request = [provider createRequest];
        request.requestedScopes = @[ASAuthorizationScopeFullName, ASAuthorizationScopeEmail];
        ASAuthorizationController *vc = [[ASAuthorizationController alloc] initWithAuthorizationRequests:@[request]];
        vc.delegate = self;
        vc.presentationContextProvider = self;
        [vc performRequests];
    }
    


}


//@optional 授权成功地回调
- (void)authorizationController:(ASAuthorizationController *)controller didCompleteWithAuthorization:(ASAuthorization *)authorization API_AVAILABLE(ios(13.0)){
    if ([authorization.credential isKindOfClass:[ASAuthorizationAppleIDCredential class]]) {
        // 用户登录使用ASAuthorizationAppleIDCredential
        ASAuthorizationAppleIDCredential *appleIDCredential = (ASAuthorizationAppleIDCredential *)authorization.credential;
//        NSString *user = appleIDCredential.user;
        
        NSString *identityToken = [[NSString alloc] initWithData:appleIDCredential.identityToken encoding:NSUTF8StringEncoding];

        [ASHUD showASLoading];
        [self gotoLoginWithLoginType:NO token:identityToken];
        
        
    }else if ([authorization.credential isKindOfClass:[ASPasswordCredential class]]){
        NSLog(@"ASPasswordCredential");
        [ASHUD hideHUD];

    }else{
        [ASHUD hideHUD];

//        NSLog(@"授权信息均不符");
    }
}



// 授权失败的回调
- (void)authorizationController:(ASAuthorizationController *)controller didCompleteWithError:(NSError *)error API_AVAILABLE(ios(13.0)){
    // Handle error.
    [ASHUD hideHUD];

    NSString *errorMsg = nil;
    switch (error.code) {
        case ASAuthorizationErrorCanceled:
            errorMsg = @"用户取消了授权请求";
            break;
        case ASAuthorizationErrorFailed:
            errorMsg = @"授权请求失败";
            break;
        case ASAuthorizationErrorInvalidResponse:
            errorMsg = @"授权请求响应无效";
            break;
        case ASAuthorizationErrorNotHandled:
            errorMsg = @"未能处理授权请求";
            break;
        case ASAuthorizationErrorUnknown:
            errorMsg = @"授权请求失败未知原因";
            break;
        default:
            break;
    }
//    ASLog(@"%@",errorMsg);
}

// 告诉代理应该在哪个window 展示内容给用户
- (ASPresentationAnchor)presentationAnchorForAuthorizationController:(ASAuthorizationController *)controller API_AVAILABLE(ios(13.0)){
    // 返回window
    return [UIApplication sharedApplication].windows.lastObject;
}


//最后登录
-(void)gotoLoginWithLoginType:(BOOL)isFastLogin token:(NSString *)token{
    kWeakSelf(weakSelf)
    [[BJNetManager shareNetManager] postLoginWithOauthType:isFastLogin?4:3 token:token completionHandler:^(id  _Nonnull responOj, NSError * _Nonnull error) {
        [ASHUD hideHUD];
        if (!error){
            NSDictionary *dict = responOj;
            NSInteger code = [dict[@"code"] integerValue];
            if(code == 0){
                [ASHUD showWithText:@"login success" afterDelay:1];
                if (weakSelf.loginSuccessCallBack){
                    weakSelf.loginSuccessCallBack(YES);
                }
                NSMutableArray *dataList2 = [NSMutableArray array];
                NSDictionary *dict2 = @{
                    @"page":@"loginsuccess",
                    @"duration":@(0),
                    @"event":@"pv",
                    @"tm":@([[BJNetManager shareNetManager] gs_getCurrentTimeToMilliSecond]),
                };
                [dataList2 addObject:dict2];
                [[BJNetManager shareNetManager]postLogWithParam:dataList2];
                
            }else{
                [ASHUD showWithText:@"login fail" afterDelay:1];
                 
            }

        }else{
            [ASHUD showWithText:@"login fail" afterDelay:1];
             
        }
    }];
}


- (UIView *)desBgView{
    if (_desBgView == nil) {
        _desBgView = View;
    }
    return _desBgView;
}

- (UIImageView *)agreeIv{
    if (_agreeIv == nil) {
        _agreeIv = ImageView.img([UIImage imageNamed:@"ic_agree_unSelect"]);
    }
    return _agreeIv;
}

 

- (YYLabel *)PrivacyPolicyLb{
    if (_PrivacyPolicyLb == nil) {
        _PrivacyPolicyLb = [[YYLabel alloc]init];
    }
   
    
    //设置整段字符串的颜色
    NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:14], NSForegroundColorAttributeName: [UIColor colorWithHexString:@"#AAAAAA"]};
    NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:@"By using our App you agree with our Terms Of Use & Privacy Policy" attributes:attributes];
    
    [text setTextHighlightRange:[[text string] rangeOfString:@"By using our App you agree with our"] color:[UIColor colorWithHexString:@"#FFFFFF"] backgroundColor:[UIColor clearColor] tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        
        self.isAgree = !self.isAgree;
        [self.agreeIv setImage:[UIImage imageNamed:self.isAgree ? @"ic_agree_select" : @"ic_agree_unSelect"]];
        
    }];
    
    //设置高亮色和点击事件
    [text setTextHighlightRange:[[text string] rangeOfString:@"Privacy Policy"] color:[UIColor colorWithHexString:@"#6CFDEE"] backgroundColor:[UIColor clearColor] tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        
        NSString *path = kPrivacyPolicyUrl;
        [self openWebViewWithPath:path title:@"Privacy Policy"];
        NSMutableArray *dataList = [NSMutableArray array];
        NSDictionary *dict = @{
            @"page":@"privacy",
            @"duration":@(0),
            @"event":@"pv",
            @"tm":@([[BJNetManager shareNetManager] gs_getCurrentTimeToMilliSecond]),
        };
        [dataList addObject:dict];
        [[BJNetManager shareNetManager]postLogWithParam:dataList];
        
    }];
    
    [text setTextHighlightRange:[[text string] rangeOfString:@"Terms Of Use"] color:[UIColor colorWithHexString:@"#6CFDEE"] backgroundColor:[UIColor clearColor] tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
        NSString *path = kUserProtocolUrl;
        [self openWebViewWithPath:path title:@"Terms Of Service"];
        NSMutableArray *dataList = [NSMutableArray array];
        NSDictionary *dict = @{
            @"page":@"terms",
            @"duration":@(0),
            @"event":@"pv",
            @"tm":@([[BJNetManager shareNetManager] gs_getCurrentTimeToMilliSecond]),
        };
        [dataList addObject:dict];
        [[BJNetManager shareNetManager]postLogWithParam:dataList];
        
    }];
    
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = 5;// 字体的行间距
    [text addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, text.length)];
    
    _PrivacyPolicyLb.attributedText = text;
    _PrivacyPolicyLb.numberOfLines = 0;
    _PrivacyPolicyLb.preferredMaxLayoutWidth = kScreenW-64  ;//设置最大宽度（YYLabel需设置这个才能换行）
    _PrivacyPolicyLb.textAlignment = NSTextAlignmentCenter;

    return _PrivacyPolicyLb;
}


- (void)openWebViewWithPath:(NSString *)path title:(NSString *)title{
    
    BJWebContentViewController *vc = [[BJWebContentViewController alloc]initWithTitle:title url:path];
    vc.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:vc animated:YES completion:nil];
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
